package sample.view;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sun.javafx.robot.impl.FXRobotHelper;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.DirectoryChooserBuilder;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import sample.model.Company;
import sample.utils.ExcelUtil;
import sample.utils.HttpRequestor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class EMapMainController {

    @FXML
    private CheckBox baidu;
    @FXML
    private CheckBox tengxun;
    @FXML
    private CheckBox gaode;
    @FXML
    private CheckBox m360;
    @FXML
    private CheckBox sogou;

    @FXML
    private Label status;

    @FXML
    public TextField area;
    @FXML
    public TextField keywords;
    @FXML
    public TableView<Company> qrTable;
    @FXML
    private TableColumn<Company, String> index;
    @FXML
    private TableColumn<Company, String> tel;
    @FXML
    private TableColumn<Company, String> name;
    @FXML
    private TableColumn<Company, String> district;
    @FXML
    private TableColumn<Company, String> address;
    @FXML
    private TableColumn<Company, String> industry;
    @FXML
    private TextField savePath;



    private Thread t;

    private MainApp main;


    private sample.utils.CrawlerPool crawlerPool;

    private int startStatus = 0 ;
    public EMapMainController() {
    }

    @FXML
    private void initialize() {

        index.setCellValueFactory(cellData -> cellData.getValue().indexProperty());
        tel.setCellValueFactory(cellData -> cellData.getValue().telProperty());
        name.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        district.setCellValueFactory(cellData -> cellData.getValue().districtProperty());
        address.setCellValueFactory(cellData -> cellData.getValue().addressProperty());
        industry.setCellValueFactory(cellData -> cellData.getValue().industryProperty());

//        qrTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> showQrImg(newValue));

   }


    public void setMain(MainApp main) {
        this.main = main;
        // Add observable list data to the table
        qrTable.setItems(main.getQrData());
    }

//    @FXML
//    public void showQrImg(Company entity) {
//        qrimg.setImage(new Image(entity.getImg()));
//    }

    @FXML
    public void handleExport(){
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel (*.xlsx)", "*.xlsx");
        fileChooser.getExtensionFilters().add(extFilter);
        Stage s = new Stage();
        File file = fileChooser.showSaveDialog(s);
        if (file == null)
            return;
        if(file.exists()){//文件已存在，则删除覆盖文件
            file.delete();
        }
        String exportFilePath = file.getAbsolutePath();
        System.out.println("导出文件的路径" + exportFilePath);


        ObservableList<Company> items = qrTable.getItems();
        List<String> list = new ArrayList<>(items.size()+1);
        list.add("名称,联系电话,省市区,详细地址,类型");
        items.forEach(x->{
            list.add(x.getName()+","+x.getTel()+","+x.getDistrict()+","+x.getAddress()+","+x.getIndustry());
        });
        try {
            ExcelUtil.writeExcel(exportFilePath, list);
        } catch (IOException e) {
            e.printStackTrace();
        }

        alert("提示", "导出成功!保存路径:\n"+exportFilePath);
    }

    @FXML
    public void upadtePath() {
        DirectoryChooserBuilder builder = DirectoryChooserBuilder.create();
        builder.title("Hello World");
        String cwd = System.getProperty("user.dir");
        File file = new File(cwd);
        builder.initialDirectory(file);
        DirectoryChooser chooser = builder.build();
        File chosenDir = chooser.showDialog(main.primaryStage);
        if (chosenDir != null) {
            savePath.setText(chosenDir.getAbsolutePath());
            System.out.println(chosenDir.getAbsolutePath());
        } else {
            System.out.print("no directory chosen");
        }
    }

    @FXML
    public void clearKeywords()
    {
        keywords.setText("");
    }


    @FXML
    public void stop()
    {
        if(crawlerPool!=null)
        {
            crawlerPool.stop();
        }
    }

    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    @FXML
    public void start()
    {

        if(!checkCheckBox())
        {
            return ;
        }

        if(keywords.getText().equals(""))
        {
            alert("行业词未输入","请输入行业关键词。");
            return;
        }

        if(area.getText().equals(""))
        {
            alert("地址未输入","请输入搜索地址。");
            return;
        }

        status.setText("状态：采集中");

        crawlerPool = new CrawlerPool(keywords.getText(),area.getText(),qrTable);
        crawlerPool.start(baidu,tengxun,gaode,m360,sogou);

    }

    private boolean checkCheckBox()
    {

        if(baidu.isSelected() ==false && tengxun.isSelected() ==false && gaode.isSelected() ==false && m360.isSelected() ==false&& sogou.isSelected() ==false)
        {
            alert("未选择电子地图","请选择一个电子地图。");

            return false;
        }

        return true;
    }

    public ButtonType confirm(String header,String content)
    {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("提示");
        alert.setHeaderText(header);
        alert.setContentText(content);

        alert.showAndWait();
        return alert.getResult();

    }

    public void alert(String header,String content)
    {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(header);
        alert.setContentText(content);

        alert.showAndWait();
    }

    public void clear() throws InterruptedException {
        if(startStatus == 1)
        {
            ButtonType buttonType = confirm("清空数据","您想停止采集并清空数据吗？");

            if(buttonType.getText().equals("确定"))
            {
                t.stop();
            }
        }
        keywords.clear();
        area.clear();
        qrTable.setItems(FXCollections.observableArrayList());
    }

    public void selectAll()
    {
        baidu.setSelected(true);
        tengxun.setSelected(true);
        gaode.setSelected(true);
        m360.setSelected(true);
        sogou.setSelected(true);
    }
    public void updateStatus()
    {
        status.setText("状态：已完成 ");
    }
}
